package com.hxhy.service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.encoding.XMLType;

import org.apache.axis.client.Call;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hxhy.bean.Account;
import com.hxhy.bean.BElectronic;
import com.hxhy.bean.Electronic;
import com.hxhy.bean.ElectronicException;
import com.hxhy.util.Tools;

import net.sf.json.JSONObject;

/**
 * 新泰新汶(远得销项发票)
 */
@Service("xtxw")
public class InvoiceServiceImpl2 extends InvoiceServiceImpl implements InvoiceService {

	@Autowired
	Electronic ele;

	public static final String csdz = "http://css.sdaisino.com:9999/FPGLXT_FW/CXF/WbService?wsdl";
	private static final String INVOICE = "sendData";
	private static final String SEARCH = "getData";
	private static final String SEND = "payInvoice";

	@Override
	public void init() {
		super.init();
	}

	@Override
	public BElectronic kpInvoice(BElectronic be) throws ElectronicException {
		return null;
	}

	@Override
	@Transactional
	public BElectronic hpInvoice(BElectronic be) throws ElectronicException {
		StringBuilder xml = new StringBuilder();
		StringBuilder mxml = new StringBuilder();
		BigDecimal kphjje = BigDecimal.ZERO;
		String lsh = Tools.getUUID();
		// 查询蓝字发票
		be = mapper.getInvoiceByFPH(be.getInvoicenum(), be.getInvoiceversion(), "正票", "电子发票");
		if (be == null) {
			error(be, "未查询到票据信息");
			throw new ElectronicException(be);
		}
		// 插入发票信息
		be.setAccountids("-1");
		be.setMoney(BigDecimal.ZERO.subtract(be.getMoney()));
		be.setInvoicekind("负票");
		be.setReturncode("0000");
		be.setReturnstate(null);
		int i = mapper.insert(be);

		if (i != 1) {
			error(be, "内部数据错误");
			throw new ElectronicException(be);
		}
		// 查询明细账目
		List<Account> acts = null;
		if (99 > be.getAccountids().split(",").length)
			acts = mapper.getFpAccountGroup(be.getAccountids());
		else
			acts = mapper.getFpAccount(be.getAccountids());
		if (0 == acts.size()) {
			error(be, "未获取到账目");
			throw new ElectronicException(be);
		}

		// 明细信息
		for (Account ac : acts) {
			kphjje = kphjje.add(ac.getReceived());
			ac.setReceivedsum(ac.getReceived());
			if (!isdutyfree(ac)) {
				ac.setReceivedsum(
						ac.getReceived().divide(BigDecimal.ONE.add(taxrate(ac)), 2, BigDecimal.ROUND_HALF_UP));
			}
			mxml.append("<InfoDetail>");
			mxml.append("<GoodsName>").append(ac.getAnnual() + "年度采暖费").append("</GoodsName>");
			mxml.append("<Standard>").append(Tools.toString(ac.getAreaname())).append("</Standard>");
			mxml.append("<Unit>").append("平方米").append("</Unit>");
			mxml.append("<Num></Num>");
			mxml.append("<Price>").append(Tools.toString(ac.getPrice())).append("</Price>");
			mxml.append("<Amount>-").append(Tools.toString(ac.getReceived())).append("</Amount>");
			mxml.append("<TaxRate>").append(Tools.toString(taxrate(ac))).append("</TaxRate>");
			mxml.append("<TaxAmount>-").append(Tools.toString(ac.getReceived().subtract(ac.getReceivedsum())))
					.append("</TaxAmount>");
			mxml.append("<Aigo>0</Aigo>");
			mxml.append("<AigoTax></AigoTax>");
			mxml.append("<GoodsGroup></GoodsGroup>");
			mxml.append("<GoodsNoVer>35.0</GoodsNoVer>");
			mxml.append("<GoodsTaxNo>1100102010100000000</GoodsTaxNo>");
			mxml.append("<GoodsTaxName>热力</GoodsTaxName>");
			mxml.append("<TaxPre>").append(isdutyfree(ac) ? "1" : "0").append("</TaxPre>");
			mxml.append("<TaxPreCon>").append(isdutyfree(ac) ? "免税" : "").append("</TaxPreCon>");
			mxml.append("<ZeroTax>").append(isdutyfree(ac) ? "1" : "").append("</ZeroTax>");
			mxml.append("<RowId></RowId>");
			mxml.append("<Remark1></Remark1>");
			mxml.append("<Remark2></Remark2>");
			mxml.append("</InfoDetail>");
		}
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><InfoMaster>");
		xml.append("<Number>").append(lsh).append("</Number>");
		xml.append("<BusNo>").append(lsh).append("</BusNo>");
		xml.append("<Organ></Organ>");
		xml.append("<ClientName>").append(Tools.toString(ele.nsrmc)).append("</ClientName>");
		xml.append("<ClientTaxCode>").append(ele.nsrsbh).append("</ClientTaxCode>");
		xml.append("<ClientBankAccount>").append(Tools.toString(ele.yhzh)).append("</ClientBankAccount>");
		xml.append("<ClientAddressPhone>").append(Tools.toString(ele.nsrdz) + Tools.toString(ele.nsrdh))
				.append("</ClientAddressPhone>");
		xml.append("<ClientPhone></ClientPhone>");
		xml.append("<ClientMail>").append(Tools.toString(Tools.toString(be.getEmail()))).append("</ClientMail>");
		xml.append("<BillType>0</BillType>");
		xml.append("<InfoKind>51</InfoKind>");
		xml.append("<Notes></Notes>");
		xml.append("<InvoiceCode>").append(Tools.toString(be.getInvoiceversion())).append("</InvoiceCode>");
		xml.append("<InvoiceNo>").append(Tools.toString(be.getInvoicenum())).append("</InvoiceNo>");
		xml.append("<Invoicer>").append(Tools.toString(ele.kpy)).append("</Invoicer>");
		xml.append("<Checker>").append(Tools.toString(ele.fhr)).append("</Checker>");
		xml.append("<Cashier>").append(Tools.toString(ele.sky)).append("</Cashier>");
		xml.append("<InvoicerCode></InvoicerCode>");
		xml.append("<SumMoney>-").append(kphjje.toPlainString()).append("</SumMoney>");
		xml.append("<Times>").append(Tools.DATEFORMAT_Y_M_D.format(new Date())).append("</Times>");
		xml.append("<SpecialInvoice></SpecialInvoice>");
		xml.append("<Remark1></Remark1>");
		xml.append("<Remark2></Remark2>");
		xml.append(mxml.toString());
		xml.append("</InfoMaster>");

		log.info("红冲发票: " + xml.toString());
		String result = web(xml.toString(), INVOICE);
		log.info(result);
		if (Tools.isNullOrEmpty(result))
			return error(be, "内部数据错误");

		JSONObject js = null;
		try {
			js = Tools.xmlToJSON(result.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			log.info(Tools.getErrorException(e));
		}
		if ("0".equals(js.getString("RetCode"))) {
			be.setReturncode("0000");
			be.setReturnstate("开票中");
			return be;
		}

		// 更新开票失败信息
		be.setReturncode("9999");
		be.setReturnstate(Tools.isNullOrEmpty(result) ? "终端连接异常" : js.getString("RetMsg"));
		mapper.update(be);

		return be;
	}

	@Override
	public BElectronic zfInvoice(BElectronic be) {
		return null;
	}

	@Override
	public void searchInvoice() {
		try {
			StringBuilder xml = new StringBuilder();
			List<BElectronic> list = mapper.kpList();
			for (BElectronic map : list) {
				xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><InfoMaster>");
				xml.append("<Number>").append(Tools.toString(map.getLsh())).append("</Number>");
				xml.append("<InvoiceCode></InvoiceCode>");
				xml.append("<InvoiceNo></InvoiceNo>");
				xml.append("<Times></Times></InfoMaster>");

				String result = web(xml.toString(), SEARCH);
				if (!Tools.isNullOrEmpty(result)) {
					JSONObject js = Tools.xmlToJSON(result.getBytes("GBK"));
					if (!"0".equals(js.getString("RetCode")))
						continue;
					JSONObject fp = js.getJSONObject("Invoice");
					String code = Tools.isNullOrEmpty(fp.getString("Pdfurl")) ? "9999" : "0000";
					String msg = fp.getString("PdfMsg");
					map.setInvoiceversion(fp.getString("InvoiceCode"));
					map.setInvoicenum(fp.getString("InvoiceNo"));
					map.setPdfpath(fp.getString("Pdfurl"));
					map.setReturncode(code);
					map.setReturnstate(msg);

					if ("0000".equals(code)) {
						if ("负票".equals(map.getInvoicekind())) {
							map.setFlag("1");
							BElectronic yfp = mapper.getInvoiceByFPH(map.getInvoicenum(), map.getInvoiceversion(), "正票",
									map.getInvoicemethod());
							yfp.setFlag("1");
							mapper.update(yfp);
							mapper.clearInvoiceById(yfp.getAccountids());
						}
						mapper.replaceInvoice(map);
					}
					mapper.update(map);
				}
			}
		} catch (Exception e) {
			log.info(Tools.getErrorException(e));
		}
	}

	@Override
	public void kp() {
		StringBuilder sql = new StringBuilder();
		try {
			List<BElectronic> list = mapper.ykpList();
			for (BElectronic fp : list) {
				fp.setReturncode("0000");
				if (Tools.isNullOrEmpty(fp.getAccountids())) {
					fp.setAccountids("-1");
				}
				fp.setAccountids(fp.getAccountids().replaceAll(",null", "").replaceAll("null,", ""));
				// 过滤重复开票信息
				int n = mapper.fpCount(fp.getAccountids());
				if (0 < n) {
					error(fp, "账目信息已开发票");
					mapper.update(fp);
					continue;
				}
				if ("负票".equals(fp.getInvoicekind())) {
					BElectronic yfp = mapper.getInvoiceByFPH(fp.getInvoicenum(), fp.getInvoiceversion(), "正票",
							fp.getInvoicemethod());
					if (yfp == null) {
						error(fp, "未获取到发票");
						mapper.update(fp);
						continue;
					}
					yfp.setActs(mapper.getFpAccount(yfp.getAccountids()));
					fp.setLsh(Tools.getUUID());
					fp.setReverselsh(yfp.getLsh());
					fp.setHouseid(yfp.getHouseid());
					fp.setMoney(BigDecimal.ZERO.subtract(yfp.getMoney()));
					fp.setEmail(yfp.getEmail());
					fp.setGfmc(yfp.getGfmc());
					fp.setNsrsbh(yfp.getNsrsbh());
					fp.setDz(yfp.getDz());
					fp.setBe(yfp);
					String xml = xmlString(fp, "2");
					log.info("自动开票:" + xml);
					String web = web(xml, SEND);
					log.info(web);
					JSONObject js = Tools.xmlToJSON(web.getBytes("UTF-8"));
					String code = "0000";
					String msg = null;
					if (!"0".equals(js.getString("RetCode"))) {
						code = "1001".equals(js.getString("RetCode")) ? "9999" : js.getString("RetCode");
						msg = js.getString("RetMsg");
					}
					fp.setHouseid(yfp.getHouseid());
					fp.setMoney(BigDecimal.ZERO.subtract(yfp.getMoney()));
					fp.setEmail(yfp.getEmail());
					fp.setGfmc(yfp.getGfmc());
					fp.setNsrsbh(yfp.getNsrsbh());
					fp.setKhh(yfp.getKhh());
					fp.setDz(yfp.getDz());
					fp.setInvoicemethod("电子发票");
					fp.setLsh(fp.getLsh());
					fp.setReverselsh(yfp.getLsh());
					fp.setKpr(ele.kpy);
					fp.setSkr(ele.sky);
					fp.setFhr(ele.fhr);
					fp.setReturncode(code);
					fp.setReturnstate(msg);

				} else {
					sql.delete(0, sql.length());
					if (80 > fp.getAccountids().split(",").length) {
						fp.setActs(mapper.getFpAccountGroup(fp.getAccountids()));
					} else {
						fp.setActs(mapper.getFpAccount(fp.getAccountids()));
					}
					fp.setLsh(Tools.getUUID());
					String xml = xmlString(fp, "1");
					log.info("自动开票:" + xml);
					String web = web(xml, SEND);
					log.info(web);
					JSONObject js = Tools.xmlToJSON(web.getBytes("UTF-8"));
					String code = "0000";
					String msg = null;
					if (!"0".equals(js.getString("RetCode"))) {
						code = "1001".equals(js.getString("RetCode")) ? "9999" : js.getString("RetCode");
						msg = js.getString("RetMsg");
					}
					fp.setInvoicemethod("电子发票");
					fp.setKpr(ele.kpy);
					fp.setSkr(ele.sky);
					fp.setFhr(ele.fhr);
					fp.setReturncode(code);
					fp.setReturnstate(msg);
				}
				mapper.update(fp);
			}
		} catch (Exception e) {
		}
	}

	@Override
	public BElectronic sendInvoice(BElectronic be) {
		// 查询发票信息
		be = mapper.getInvoiceByFPH(be.getInvoicenum(), be.getInvoiceversion(), be.getInvoicekind(), "电子发票");

		String result = web(xmlString(be, "3"), SEND);
		if (Tools.isNullOrEmpty(result))
			return error(be, "内部数据错误");

		JSONObject js = null;
		try {
			js = Tools.xmlToJSON(result.getBytes("GBK"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		if ("0".equals(js.getString("RetCode"))) {
			be.setReturncode("0000");
			be.setReturnstate("已发送");
			return be;
		}

		return error(be, "内部数据错误");
	}

	/**
	 * 发送请求
	 * 
	 * @param xml
	 * @param method
	 * @return
	 */
	public String web(String xml, String method) {
		String result = null;
		try {
			String url = "http://css.sdaisino.com:9999/FPGLXT_FW/CXF/WbService";
			String space = "com.htxx.service";

			org.apache.axis.client.Service ser = new org.apache.axis.client.Service();
			Call call = (Call) ser.createCall();
			call.setTargetEndpointAddress(new URL(url));
			call.setOperationName(new QName(space, method));
			call.setUseSOAPAction(true);
			call.addParameter(new QName("arg0"), XMLType.XSD_STRING, ParameterMode.IN);
			call.setReturnType(XMLType.XSD_STRING);
			result = (String) call.invoke(new Object[] { xml });
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 拼接开票xml
	 * 
	 * @param e
	 * @param lx
	 * @return
	 */
	public String xmlString(BElectronic e, String lx) {
		StringBuilder xml = new StringBuilder();
		StringBuilder mxml = new StringBuilder();
		BigDecimal kphjje = BigDecimal.ZERO;
		if ("1".equals(lx)) {// 蓝票
			List<String> houseids = new ArrayList<String>();
			// 明细信息
			for (Account ac : e.getActs()) {
				kphjje = kphjje.add(ac.getReceived());
				if (!houseids.contains(ac.getHouseid()))
					houseids.add(ac.getHouseid());
				mxml.append("<InfoDetail>");
				mxml.append("<GoodsName>").append(Tools.toString(ac.getAnnual().concat("年度采暖费")))
						.append("</GoodsName>");
				mxml.append("<Standard>").append(Tools.toString(ac.getAreakind())).append("</Standard>");
				mxml.append("<Unit>平方米</Unit>");
				mxml.append("<Num></Num>");
				mxml.append("<Price>").append(Tools.toString(ac.getPrice())).append("</Price>");
				mxml.append("<Amount>").append(Tools.toString(ac.getReceived())).append("</Amount>");
				mxml.append("<TaxRate>").append(Tools.toString(ac.getSl())).append("</TaxRate>");
				mxml.append("<TaxAmount>").append(Tools.toString(ac.getSe())).append("</TaxAmount>");
				mxml.append("<Aigo>0</Aigo>");
				mxml.append("<AigoTax></AigoTax>");
				mxml.append("<GoodsGroup></GoodsGroup>");
				mxml.append("<GoodsNoVer>35.0</GoodsNoVer>");
				mxml.append("<GoodsTaxNo>1100102010100000000</GoodsTaxNo>");
				mxml.append("<GoodsTaxName>热力</GoodsTaxName>");
				mxml.append("<TaxPre>").append(0 == BigDecimal.ZERO.compareTo(ac.getSl()) ? "1" : "0")
						.append("</TaxPre>");
				mxml.append("<TaxPreCon>").append(0 == BigDecimal.ZERO.compareTo(ac.getSl()) ? "免税" : "")
						.append("</TaxPreCon>");
				mxml.append("<ZeroTax>").append(0 == BigDecimal.ZERO.compareTo(ac.getSl()) ? "1" : "")
						.append("</ZeroTax>");
				mxml.append("<RowId></RowId>");
				mxml.append("<Remark1></Remark1>");
				mxml.append("<Remark2></Remark2>");
				mxml.append("</InfoDetail>");
			}
			e.setMoney(kphjje);
			e.setHouseid(houseids.toString());
			xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><InfoMaster>");
			xml.append("<Number>").append(e.getLsh()).append("</Number>");
			xml.append("<BusNo>").append(e.getLsh()).append("</BusNo>");
			xml.append("<Organ></Organ>");
			xml.append("<ClientName>").append(Tools.toString(ele.nsrmc)).append("</ClientName>");
			xml.append("<ClientTaxCode>").append(ele.nsrsbh).append("</ClientTaxCode>");
			xml.append("<ClientBankAccount>").append(Tools.toString(ele.yhzh)).append("</ClientBankAccount>");
			xml.append("<ClientAddressPhone>").append(Tools.toString(ele.nsrdz) + Tools.toString(ele.nsrdh))
					.append("</ClientAddressPhone>");
			xml.append("<ClientPhone>").append(Tools.toString(e.getTel())).append("</ClientPhone>");
			xml.append("<ClientMail>").append(Tools.toString(e.getEmail())).append("</ClientMail>");
			xml.append("<BillType>1</BillType>");
			xml.append("<InfoKind>51</InfoKind>");
			xml.append("<Notes>").append(Tools.toString(e.getRemark())).append("</Notes>");
			xml.append("<InvoiceCode></InvoiceCode>");
			xml.append("<InvoiceNo></InvoiceNo>");
			xml.append("<Invoicer>").append(Tools.toString(ele.kpy)).append("</Invoicer>");
			xml.append("<Checker>").append(Tools.toString(ele.fhr)).append("</Checker>");
			xml.append("<Cashier>").append(Tools.toString(ele.sky)).append("</Cashier>");
			xml.append("<InvoicerCode></InvoicerCode>");
			xml.append("<SumMoney>").append(kphjje.toPlainString()).append("</SumMoney>");
			xml.append("<Times>").append(Tools.DATEFORMAT_Y_M_D.format(new Date())).append("</Times>");
			xml.append("<SpecialInvoice></SpecialInvoice>");
			xml.append("<Remark1></Remark1>");
			xml.append("<Remark2></Remark2>");
			xml.append(mxml.toString());
			xml.append("</InfoMaster>");
		} else if ("2".equals(lx)) {// 红票
			// 明细信息
			for (Account ac : e.getBe().getActs()) {
				kphjje = kphjje.add(ac.getReceived());
				mxml.append("<InfoDetail>");
				mxml.append("<GoodsName>").append(Tools.toString(ac.getAnnual().concat("年度采暖费")))
						.append("</GoodsName>");
				mxml.append("<Standard>").append(Tools.toString(ac.getAreakind())).append("</Standard>");
				mxml.append("<Unit>平方米</Unit>");
				mxml.append("<Num></Num>");
				mxml.append("<Price>").append(Tools.toString(ac.getPrice())).append("</Price>");
				mxml.append("<Amount>-").append(Tools.toString(ac.getReceived())).append("</Amount>");
				mxml.append("<TaxRate>").append(Tools.toString(ac.getSl())).append("</TaxRate>");
				mxml.append("<TaxAmount>-").append(Tools.toString(ac.getSe())).append("</TaxAmount>");
				mxml.append("<Aigo>0</Aigo>");
				mxml.append("<AigoTax></AigoTax>");
				mxml.append("<GoodsGroup></GoodsGroup>");
				mxml.append("<GoodsNoVer>35.0</GoodsNoVer>");
				mxml.append("<GoodsTaxNo>1100102010100000000</GoodsTaxNo>");
				mxml.append("<GoodsTaxName>热力</GoodsTaxName>");
				mxml.append("<TaxPre>").append(0 == BigDecimal.ZERO.compareTo(ac.getSl()) ? "1" : "0")
						.append("</TaxPre>");
				mxml.append("<TaxPreCon>").append(0 == BigDecimal.ZERO.compareTo(ac.getSl()) ? "免税" : "")
						.append("</TaxPreCon>");
				mxml.append("<ZeroTax>").append(0 == BigDecimal.ZERO.compareTo(ac.getSl()) ? "1" : "")
						.append("</ZeroTax>");
				mxml.append("<RowId></RowId>");
				mxml.append("<Remark1></Remark1>");
				mxml.append("<Remark2></Remark2>");
				mxml.append("</InfoDetail>");
			}
			e.setMoney(kphjje);
			xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><InfoMaster>");
			xml.append("<Number>").append(e.getLsh()).append("</Number>");
			xml.append("<BusNo>").append(e.getLsh()).append("</BusNo>");
			xml.append("<Organ></Organ>");
			xml.append("<ClientName>").append(Tools.toString(ele.nsrmc)).append("</ClientName>");
			xml.append("<ClientTaxCode>").append(ele.nsrsbh).append("</ClientTaxCode>");
			xml.append("<ClientBankAccount>").append(Tools.toString(ele.yhzh)).append("</ClientBankAccount>");
			xml.append("<ClientAddressPhone>").append(Tools.toString(ele.nsrdz) + Tools.toString(ele.nsrdh))
					.append("</ClientAddressPhone>");
			xml.append("<ClientPhone></ClientPhone>");
			xml.append("<ClientMail>").append(Tools.toString(Tools.toString(e.getBe().getEmail())))
					.append("</ClientMail>");
			xml.append("<BillType>0</BillType>");
			xml.append("<InfoKind>51</InfoKind>");
			xml.append("<Notes></Notes>");
			xml.append("<InvoiceCode>").append(Tools.toString(e.getBe().getInvoiceversion())).append("</InvoiceCode>");
			xml.append("<InvoiceNo>").append(Tools.toString(e.getBe().getInvoicenum())).append("</InvoiceNo>");
			xml.append("<Invoicer>").append(Tools.toString(ele.kpy)).append("</Invoicer>");
			xml.append("<Checker>").append(Tools.toString(ele.fhr)).append("</Checker>");
			xml.append("<Cashier>").append(Tools.toString(ele.sky)).append("</Cashier>");
			xml.append("<InvoicerCode></InvoicerCode>");
			xml.append("<SumMoney>-").append(kphjje.toPlainString()).append("</SumMoney>");
			xml.append("<Times>").append(Tools.DATEFORMAT_Y_M_D.format(new Date())).append("</Times>");
			xml.append("<SpecialInvoice></SpecialInvoice>");
			xml.append("<Remark1></Remark1>");
			xml.append("<Remark2></Remark2>");
			xml.append(mxml.toString());
			xml.append("</InfoMaster>");
		} else if ("3".equals(lx)) {// 推送
			xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><InfoMaster>");
			xml.append("<InvoiceCode>").append(e.getInvoiceversion()).append("</InvoiceCode>");
			xml.append("<InvoiceNo>").append(e.getInvoicenum()).append("</InvoiceNo>");
			xml.append("<Times>").append(e.getInvoicetime()).append("</Times>");
			xml.append("<ClientMail>").append(Tools.toString(e.getEmail())).append("</ClientMail>");
			xml.append("<ClientPhone>").append(Tools.toString(e.getTel())).append("</ClientPhone>");
			xml.append("</InfoMaster>");
		} else if ("s".equals(lx)) {// 查询

		}

		return xml.toString();
	}

}
